package com.gzcstec.stmp.factory;

import com.gzcstec.stmp.config.StmpPoolConfig;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.Session;

/**
 * stmp 回话对象连接池
 */
@Component
public class StmpPool {

    private static Logger logger = LoggerFactory.getLogger(StmpPool.class);

    /**
     * 连接池集合对象
     */
    private GenericObjectPool<Session> sessionGenericObjectPool;

    @Autowired
    private StmpPoolConfig stmpPoolConfig;

    @Autowired
    private StmpFactory stmpFactory;

    /**
     * 获取session对象
     * @return
     * @throws Exception
     */
    public Session borrowObject() throws Exception {

        if(sessionGenericObjectPool == null) {
            GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
            poolConfig.setBlockWhenExhausted(stmpPoolConfig.getBlockWhenExhausted());
            poolConfig.setMaxWaitMillis(stmpPoolConfig.getMaxWait());
            poolConfig.setMinIdle(stmpPoolConfig.getMinIdle());
            poolConfig.setMaxIdle(stmpPoolConfig.getMaxIdle());
            poolConfig.setMaxTotal(stmpPoolConfig.getMaxTotal());
            poolConfig.setTestOnBorrow(stmpPoolConfig.getTestOnBorrow());
            poolConfig.setTestOnReturn(stmpPoolConfig.getTestOnReturn());
            poolConfig.setTestOnCreate(stmpPoolConfig.getTestOnCreate());
            poolConfig.setTestWhileIdle(stmpPoolConfig.getTestWhileIdle());
            poolConfig.setLifo(stmpPoolConfig.getLifo());

            // 初始化对象池
            sessionGenericObjectPool = new GenericObjectPool<Session>(stmpFactory, poolConfig);
            logger.debug("构建stmp连接池");
        }
        return sessionGenericObjectPool.borrowObject();
    }

    /**
     * 释放连接
     * @param session
     */
    public void returnObject(Session session) {
        sessionGenericObjectPool.returnObject(session);
    }
}
